// --------------------------------------------------------------------
//   name 	: 
//   desc 	: 
//   version 	: 
//   dev 	: 
// --------------------------------------------------------------------
// DEPENDENCIES
// 
// --------------------------------------------------------------------
// CHANGE HISTORY
// 0.1 	Initial Release
// --------------------------------------------------------------------
	plugins.enhanceOverview = { // Enhance the village overview page
		'enhance_game_overview_villages' : function() { // Clean up and enhance the village overview

			var vils = twe.myVillages();
			if ($("a[href*=memo]").length == 0) {

			var TW_Image_Base = personals.getImageBase();
			var vilgrps = personals.villageGroups();
			var vils = twe.myVillages();
			//alert(vils);
			var multivillage=false;
			for(var v in vils) { if(v!=twe.curVillage) { multivillage = true; break; } }

			var groupConfigStart = '<div id="groupConfig">';
			var groupConfig = '<div><a href="javascript:toggleGroupConfig();">'+twe.lang("group_toggle")+'</a></div>';
			groupConfig += '<div id="groupConfigSub" style="display: none;">';
			groupConfig += '<table class="vis">';
			groupConfig += '<tr><th>'+twe.lang("group_name")+'</th><th>'+twe.lang("group_action")+'</th></tr>';

			if (vilgrps.length > 0) {
				for (i = 0; i < vilgrps.length; i++) {
					var tmpgrp = eval(vilgrps[i]);
					if (tmpgrp.id.toString() != 'undefined') {
						if (vilgrps.length > 1 && (vilgrps.length -1) ==  i) { // bottom row
							groupConfig += '<tr><td><table><tr><td width="20" align="center" colspan="1">';
							groupConfig += '<img src="' + TW_Image_Base + 'oben.png" title=" ' + twe.lang("group_moveup") + ' " onclick="moveGroup(\'u\',\''+tmpgrp.id+'\');" />';
							groupConfig += '</td><td>';
							groupConfig += '<input type="text" id="grp_'+tmpgrp.id+'" name="grp_'+tmpgrp.id+'" value="'+tmpgrp.name+'" onchange="groupChange(\''+tmpgrp.id+'\');" onmouseout="groupChange(\''+tmpgrp.id+'\');" />';
							groupConfig += '</td></tr></table>';
							groupConfig += '</td><td><a id="drop_'+tmpgrp.id+'" href="javascript:dropGroup(\''+tmpgrp.id+'\');">'+twe.lang("group_remove")+'</a> <a style="display: none;" href="javascript:editGroup(\''+tmpgrp.id+'\');" id="edit_'+tmpgrp.id+'">'+twe.lang("group_edit")+'</a></td></tr>';
						} else if (vilgrps.length > 1 && i !== 0) { // middle rows
							groupConfig += '<tr><td><table><tr><td width="20" align="center">';
		                            //    groupConfig += '<img src="' + TW_Image_Base + 'unten.png" title=" ' + twe.lang("group_movedown") + ' " onclick="moveGroup(\'d\',\''+tmpgrp.id+'\');" />';
		                            //    groupConfig += '</td><td width="20">';
							groupConfig += '<img src="' + TW_Image_Base + 'oben.png" title=" ' + twe.lang("group_moveup") + ' " onclick="moveGroup(\'u\',\''+tmpgrp.id+'\');" />';
							groupConfig += '</td><td>';
							groupConfig += '<input type="text" id="grp_'+tmpgrp.id+'" name="grp_'+tmpgrp.id+'" value="'+tmpgrp.name+'" onchange="groupChange(\''+tmpgrp.id+'\');" onmouseout="groupChange(\''+tmpgrp.id+'\');" />';
							groupConfig += '</td></tr></table>';
							groupConfig += '</td><td><a id="drop_'+tmpgrp.id+'" href="javascript:dropGroup(\''+tmpgrp.id+'\');">'+twe.lang("group_remove")+'</a> <a style="display: none;" href="javascript:editGroup(\''+tmpgrp.id+'\');" id="edit_'+tmpgrp.id+'">'+twe.lang("group_edit")+'</a></td></tr>';
						} else if (vilgrps.length > 1 && i === 0) { // top row
							groupConfig += '<tr><td><table><tr><td width="20" align="center" colspan="1">';
		                           //     groupConfig += '<img src="' + TW_Image_Base + 'unten.png" title=" ' + twe.lang("group_movedown") + ' " onclick="moveGroup(\'d\',\''+tmpgrp.id+'\');" />';
							groupConfig += '</td><td>';
							groupConfig += '<input type="text" id="grp_'+tmpgrp.id+'" name="grp_'+tmpgrp.id+'" value="'+tmpgrp.name+'" onchange="groupChange(\''+tmpgrp.id+'\');" onmouseout="groupChange(\''+tmpgrp.id+'\');" />';
							groupConfig += '</td></tr></table>';
							groupConfig += '</td><td><a id="drop_'+tmpgrp.id+'" href="javascript:dropGroup(\''+tmpgrp.id+'\');">'+twe.lang("group_remove")+'</a> <a style="display: none;" href="javascript:editGroup(\''+tmpgrp.id+'\');" id="edit_'+tmpgrp.id+'">'+twe.lang("group_edit")+'</a></td></tr>';

						} else {
							groupConfig += '<tr><td><table><tr><td width="40" align="center" colspan="2">';
							groupConfig += '</td><td>';
							groupConfig += '<input type="text" id="grp_'+tmpgrp.id+'" name="grp_'+tmpgrp.id+'" value="'+tmpgrp.name+'" onchange="groupChange(\''+tmpgrp.id+'\');" onmouseout="groupChange(\''+tmpgrp.id+'\');" />';
							groupConfig += '</td></tr></table>';
							groupConfig += '</td><td><a id="drop_'+tmpgrp.id+'" href="javascript:dropGroup(\''+tmpgrp.id+'\');">'+twe.lang("group_remove")+'</a> <a style="display: none;" href="javascript:editGroup(\''+tmpgrp.id+'\');" id="edit_'+tmpgrp.id+'">'+twe.lang("group_edit")+'</a></td></tr>';
						}
					}
				}
			}
			groupConfig += '<tr class="add"><td><input type="text" name="grp_add" id="grp_add" /></td><td><a href="javascript:addGroup();">'+twe.lang("group_add")+'</a></td></tr>';     
			groupConfig += '</table>';

			if (vilgrps.length > 0 && multivillage) {
				var grps = vilgrps;
				groupConfig += '<table id="groupSelection">';
				groupConfig += '<tr>';
				groupConfig += '<th colspan="3">'+twe.lang("group_village")+'</th><th>'+twe.lang("group_ingroup")+'</th>';
				groupConfig += '</tr>';
	
				for (var j in vils) {
					var curvil = vils[j];
					if (new String(curvil.name) == 'undefined') { break; }
					groupConfig += '<tr>';
					if (curvil.alias) {
						groupConfig += '<td>'+decodeURIComponent(curvil.alias)+'</td>';
						groupConfig += '<td>['+curvil.x+'|'+curvil.y+']</td>';
						groupConfig += '<td>K'+curvil.continent+'&nbsp;</td>';
					} else {
						groupConfig += '<td>'+decodeURIComponent(curvil.name)+'</td>';
						groupConfig += '<td>['+curvil.x+'|'+curvil.y+']</td>';
						groupConfig += '<td>K'+curvil.continent+'&nbsp;</td>';
					}
					groupConfig += '<td><select name="vil_'+curvil.id+'" id="vil_'+j+'">';
					groupConfig += '<option value="0">--'+twe.lang("group_nogroup")+'--</option>';
					for (ik = 0; ik < grps.length; ik++) {
						var tmpgrp = eval(grps[ik]);
						if (tmpgrp.id.toString() != 'undefined') {
							groupConfig += '<option value="'+tmpgrp.id+'" '+(vils[j].group == tmpgrp.id ? 'selected="selected"':"")+'>'+tmpgrp.name+'</option>';
						}
					}
					groupConfig += '</select></td>';
					groupConfig += '</tr>';
				}
				groupConfig += '<tr><td colspan="3">&nbsp;</td><td>';
				groupConfig += '<a href="javascript:storeGroup();">'+twe.lang("group_store")+'</a>';
				groupConfig += '<div id="storeGroupMessage" style="display: none;">'+twe.lang("group_storeDone")+'</div>';
				groupConfig += '</td></tr>';
				groupConfig += '</table></div>';
			}

			var groupConfigEnd = '</div>';
			setFunc("groupChange", function(ident) {
				window.setTimeout(function() {
					var cur = personals.villageGroups();

					for (i =0; i < cur.length; i++) {
						var tmp = eval(cur[i]);
						if (tmp.id == ident && tmp.name != $("#grp_"+ident).val()) {
							$("#edit_"+ident).css({display: "block"});
							$("#drop_"+ident).css({display: "none"});
						}
					}
				}, 0);
			});
			setFunc("moveGroup", function(pos, id) {
				window.setTimeout(function() {
					var curGrps = personals.villageGroups();
					var newcur = [];

					for (i =0; i < curGrps.length; i++) {
						var cur = eval(curGrps[i]);
						var oldcur;
						if (i !== 0) {
							oldcur = eval(curGrps[(i-1)]);
						}
						if (pos == 'u' && cur.id == id) {
							newcur[i] = oldcur.id;
							newcur[(i -1)] = cur.id;
							$("#groupListItem_"+cur.id).insertBefore("#groupListItem_"+oldcur.id);
						} else {
							newcur[i] = cur.id;
						}
					}
					setValue("villageGroups", newcur);

					p = plugins.enhanceOverview;
					p.enhance_game_overview_villages();
				}, 0);
			});
			setFunc("dropGroup", function(ident) {
				window.setTimeout(function() {
					delValue("GroupInfo_"+ident);
					var cur = personals.villageGroups();
					var newcur = [];
					for (i =0; i < cur.length; i++) {
						var tmp = eval(cur[i]);
						if (tmp.id != ident) {
							newcur.push(tmp.id);
						}
					}
					cur = newcur;
					setValue("villageGroups", cur);

					p = plugins.enhanceOverview;
					p.enhance_game_overview_villages();

					$("#groupListItem_"+ident+" tr:first").remove();
					$("#groupListItem_"+ident+" tr").appendTo("#groupListContainer_0");
					$("#groupListItem_0").css({"display":"block"});
					$("#groupListItem_"+ident).remove();
				}, 0);
			});
			setFunc("addGroup", function() {
				window.setTimeout(function() {
					var val = $("#grp_add").val();
					var cur = personals.villageGroups();
					var hash = '';
					while (hash.length < 8) {
						hash += Math.random();
					}
					hash = hash.substr(2);
					if (cur.length === 0) {
						cur = [hash];
					} else {
						var newcur = [];
						for (i =0; i < cur.length; i++) {
							var tmp = eval(cur[i]);
							newcur.push(tmp.id);
						}
						newcur.push(hash);
						cur = newcur;
					}
					setValue("villageGroups", cur);
					setValue("GroupInfo_"+hash, {"name":val});
					p = plugins.enhanceOverview;
					p.enhance_game_overview_villages();
				}, 0);
			});
			setFunc("editGroup", function(ident) {
				window.setTimeout(function() {
					var newval = $("#grp_"+ident).val();
					var grp = getValue("GroupInfo_"+ident);
					grp.name = newval;
					setValue("GroupInfo_"+ident, grp);
					$("#groupListItem_"+ident+" div.header a").html(newval);
					p = plugins.enhanceOverview;
					p.enhance_game_overview_villages();
				}, 0);
			});
			setFunc("storeGroup", function() {
				window.setTimeout(function() {
					var vilgrps = $("#groupSelection select");
					
					for (i = 0; i < vilgrps.length; i++) {
						try {
							var tmp = new String(getValue("villageinfo_"+vilgrps[i].name.substr(4)));
						}
						catch (e) {
							var tmp = 'undefined';
						}
						if (tmp != 'undefined') {
							tmp = tmp.split(",");

							setValue("villageinfo_"+vilgrps[i].name.substr(4), ""+vilgrps[i].value+","+tmp[1]);
						} else {
							setValue("villageinfo_"+vilgrps[i].name.substr(4), ""+vilgrps[i].value+",");
						}
					}

					personals.getUserVillages();

					$("#storeGroupMessage").fadeIn("slow");
					document.location.reload();
				}, 0);
			});
		
			$("table.main table.vis:first").css({width: "100%"});
			if ($("table.main table.vis").length > 1) {
				$("table.main table.vis:last").css({width: "35%","display":"none"});
			}
			if ($("#groupConfig").length > 0) {
				$("#groupConfig").html(groupConfig);
				$("#groupConfigSub").toggle();
			} else {
				$("table.main table.vis:last").after(groupConfigStart+groupConfig+groupConfigEnd);
			}
		
			setFunc("toggleGroupConfig", function() {
				$("#groupConfigSub").toggle();
			});
		
		// }}} GROUP BIT
		// {{{ CLEANUP BIT
		
			setFunc("toggleGroup", function(id) {
				$("#groupListContainerWrapper_"+id).slideToggle("slow", function() {
					if (id != 0) {
					window.setTimeout(function() {
						var tmp = getValue("GroupInfo_"+id);
						if ($("#groupListContainerWrapper_"+id)[0].style.display != 'block') {
							tmp.show = 0;
						} else {
							tmp.show = 1;
						}
						setValue("GroupInfo_"+id, tmp);
					}, 0);
					}
				});
		        //$("#groupListContainer_"+id).css({"width":"100%"});
			});
		
			var grps = vilgrps;
		
			var disp;
			if (getVar("grp_0") === 0) {
				disp = 'style="display: none"';
			} else {
				disp = '';
			}
			var grpList = '<div id="groupList">';
			grpList += '<div id="groupListItem_0" class="groups">';
			grpList += '<div class="header"><a href="javascript:toggleGroup(\'0\');">'+twe.lang("overview_nogroup")+'</a></div>';
			grpList += '<div id="groupListContainerWrapper_0" '+disp+'><table class="groupContainers" id="groupListContainer_0"></table></div></div>';
			for (i = 0; i < grps.length; i++) {
				eval("var tmp = "+grps[i]);

				var tmpgrpinfo = getValue("GroupInfo_"+tmp.id);
				if (tmpgrpinfo.show == 0) {
					disp = 'style="display: none"';
				} else {
					disp = '';
				}

				grpList += '<div id="groupListItem_'+tmp.id+'" class="groups">';
				grpList += '<div class="header"><a href="javascript:toggleGroup(\''+tmp.id+'\');">'+tmp.name+'</a></div>';
				grpList += '<div id="groupListContainerWrapper_'+tmp.id+'" '+disp+'><table class="groupContainers" id="groupListContainer_'+tmp.id+'"></table></div></div>';
			}
			grpList += '</div>';
		
			if ($("table.main table.vis").length == 4) {
				$("table.main table.vis")[0].style.display = 'none';
				$("table.main table.vis")[1].style.display = 'none';
			} else {
				$("table.main table.vis:first").css({"display":"none"});
			}
			if ($("#groupList").length === 0) {
				$("table.main table.vis:first").after(grpList);
			} else {
				$("#groupList table.groupContainers").each(function() {this.innerHTML = '';});
			}
		
			var grps = getValue("villageGroups");
			$("table.vis tr.row_a, table.vis tr.row_b").addClass("villagerow"); // Fix for not messing up the sorting of villages
			$("table.vis tr.villagerow").each(function() {
				var tmpId = this.innerHTML.match( /village=([^&]+)/ );

				var cache = [];

				for (var identi in vils) {
					tmp = vils[identi];

					if (tmp && tmp.id == tmpId[1]) {
						if (grps && grps.indexOf(tmp.group) != -1) {

							$(this).clone().appendTo("#groupListContainer_"+tmp.group);
							cache.push(tmpId[1]);
						}
					}
				}
				if (cache.indexOf(tmpId[1]) == -1) {
					$(this).clone().appendTo("#groupListContainer_0");
				}
			});

			$("#groupList div.groups table tr").each(function() {
		
		
				var tmpId = this.innerHTML.match( /village=([^&]+)/ );
				var alias = '';
				for (identi in vils) {
					tmp = vils[identi];
				//for (i = 0; i < vils.length; i++) {
					//var tmp =vils[i];
					//alert(tmp);
					if (tmp && tmp.id == tmpId[1]) {
						alias = tmp.alias;
						
					}
				}
		
				var tmp = this.innerHTML;
				tmp = tmp.replace(/\n|\r|\t/gi, "");
				if (alias !== '') {
					tmp = tmp.replace(/<td><span id="label_([0-9]+)"><a href="(.+)screen=([a-zA-Z]+)([^"]+)">(.*)<span id="label_text_([0-9]+)">(.+) \(([0-9]+)\|([0-9]+)\) K([0-9]+)<\/span><\/a><\/span>(.+)<\/td><td>(.+)<\/td><td>(.+)<\/td><td>(.+)<\/td>/gi, "<td><table class=\"village\"><tr><td class=\"village_name\"><a href=\"$2screen=$3$4\" title=\"$6\">$5"+alias+"</a></td><td class=\"village_map\"><a href=\"$2screen=map$4\">($8|$9)</a></td><td class=\"village_continent\">K$10</td></tr></table></td><td>$12</td><td>$13</td><td>$14</td>");
				} else {
					tmp = tmp.replace(/<td><span id="label_([0-9]+)"><a href="(.+)screen=([a-zA-Z]+)([^"]+)">(.*)<span id="label_text_([0-9]+)">(.+) \(([0-9]+)\|([0-9]+)\) K([0-9]+)<\/span><\/a><\/span>(.+)<\/td><td>(.+)<\/td><td>(.+)<\/td><td>(.+)<\/td>/gi, "<td><table class=\"village\"><tr><td class=\"village_name\"><a href=\"$2screen=$3$4\">$5$7</a></td><td class=\"village_map\"><a href=\"$2screen=map$4\">($8|$9)</a></td><td class=\"village_continent\">K$10</td></tr></table></td><td>$12</td><td>$13</td><td>$14</td>");
				}
				tmp = tmp.replace(/<td align="center"><img(.+)<img(.+)<img(.+)<\/td><td>(.+)<\/td><td>(.+)<\/td>/gi, "<td><table class=\"resources\"><tr><td><img$1</td><td><img$2</td><td><img$3</td></tr></table></td><td>$4</td><td>$5</td>");

		        //SETTING: FARM SPACE
				farm = tmp.match(/(\d+)\/(\d+)/);
				farm[3] = (farm[2] - farm[1]);
				tmp = tmp.replace(/(\d+)\/(\d+)/gi, farm[3]+" ($2)");

				$(this).html(tmp);
			});
		
			//$("#groupList table.groupContainers tr.villagerow:odd").css({border:"1px solid red"});
			
			$("#groupList table.groupContainers").each(function() {
				var toprow = "<tr><th class=\"village\">"+twe.lang('overview_village')+"</th>";
				toprow += "<th class=\"points\">"+twe.lang('overview_points')+"</th>";
				toprow += "<th class=\"resources\">"+twe.lang('overview_resources')+"</th>";
				toprow += "<th class=\"warehouse\">"+twe.lang('overview_warehouse')+"</th>";
				toprow += "<th>"+twe.lang('overview_farm')+"</th></tr>";

				$(toprow).prependTo(this);
			});
			$("#groupList table.groupContainers tr.villagerow:even").addClass("odd");
			$("#groupList div.groups").each(function() {
				if (this.getElementsByTagName("tr").length == 1) {
					this.style.display = "none";
				}
			});
		// }}} CLEANUP BIT
		} // Close premium if
		},
  'info' : {
	  'mandatory' : false,
   'name' : "Enhanced overview",
   'desc' : "Enhance the overview page, add groups and a neater layout",
   'version' : "0.1",
   'dev' : "Timas"
  }
	};
